import React, { Component } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Upload, UploadProps, message } from 'antd';
import { windowUrl } from '@/../public/global';
import { getToken } from '@/utils/utils';
import { fromJS } from 'immutable';
import SliceUpload from '@/components/common/sliceUpload';
import { getOptAuthHeaders } from '@/utils/common';

const action = `${windowUrl}/common/upload/all`;

interface iListType {
  fileName: string;
  fileUrl: string;
  [propName: string]: any;
}
interface iFileListType {
  name: string;
  uid: string | number;
  [propName: string]: any;
}
interface iStateType {
  fileList: Array<iFileListType>;
}
let fileType = 0;

export default class upLoadFile extends Component<any, iStateType> {
  state = {
    fileList: [],
    closeFlag: false,
  };
  upLoadRef = React.createRef();
  setData = (list: Array<iListType>) => {
    const newList = fromJS(list || []).toJS();
    newList.forEach((e: iListType) => {
      e.uid = new Date().getTime();
      e.name = e.fileName;
      e.url = e.fileUrl;
    });
    this.setState({
      fileList: newList,
    });
    this?.upLoadRef?.setData(newList);
  };
  componentDidMount() {
    this.setState({
      closeFlag: true,
    });
  }
  componentWillUnmount() {
    this.setState({
      closeFlag: false,
    });
  }
  //  文件上传
  handleFileChange = info => {
    // const { uploadSuccess } = this.props;
    const { fileList, file } = info;
    const newList = this.removeList(fileList, file);
    console.log(55, info);

    if (
      file.status === 'done' &&
      file.response &&
      file.response.statusCode === '0' &&
      file.response.data
    ) {
      message.success(`${file.name} 上传成功`);
      // uploadSuccess(file.response.data.fileUrl);
    } else if (file.status === 'done' && file.response && file.response.statusCode !== '0') {
      message.error(file.response.statusMessage);
      this.setState({ fileList: newList });
      return;
    } else if (file.status === 'removed') {
      message.success('删除成功');
      return;
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`);
      this.setState({ fileList: newList });
      return;
    } else if (!file.status) {
      this.setState({ fileList: newList });
      return;
    }
    this.setState({ fileList });
  };
  // 文件删除
  handleRemove = (file: any) => {
    const { fileList } = this.state;
    const newList = this.removeList(fileList, file);
    this.setState({ fileList: newList });
  };
  removeList = (fileList: any, file: any) => {
    const newList = fromJS(fileList).toJS();
    const i = newList.findIndex(e => e.uid === file.uid);
    if (i >= 0) {
      newList.splice(i, 1);
    }
    return newList;
  };
  // 文件上传前校验
  beforeFileUpload = file => {
    const { fileMaxSize = 10, suffix = '' } = this.props;
    // 文件后缀校验
    if (suffix) {
      let flag = false;
      const suffixItem = suffix.split(',');
      suffixItem.forEach(item => {
        if (file.name.endsWith(`.${item}`)) flag = true;
      });
      if (!flag) {
        message.error(`上传文件格式有误，仅支持${suffix}文件！`);
        return false;
      }
    }
    if (file.size / 1024 / 1024 > fileMaxSize) {
      message.error(`文件大小不能大于${fileMaxSize}MB！`);
      return false;
    }
    // 允许上传图片
    const imgList = ['gif', 'jpg', 'jpeg', 'png', 'bmp'];
    const isImg = imgList.find(item => {
      return file.name.endsWith(`.${item}`);
    });
    fileType = isImg ? 1 : 0;
    return true;
  };
  render() {
    const { closeFlag } = this.state;
    const propsData: UploadProps = {
      onRef: ref => (this.upLoadRef = ref),
      action,
      listType: 'picture',
      headers: {
        OptAuthorization: `${getToken()}`,
        ...getOptAuthHeaders(),
      },
      multiple: false,
      fileList: this.state.fileList,
      onChange: this.handleFileChange,
      beforeUpload: this.beforeFileUpload,
      onRemove: this.handleRemove,
      closeFlag,
      data: file => {
        return {
          fileType,
        };
      },
    };
    return (
      //   <Upload {...propsData}>
      <SliceUpload {...propsData}>
        <Button icon={<UploadOutlined />}>上传</Button>
      </SliceUpload>
      //   </Upload>
    );
  }
}
